package com.ujoku.controller;

import com.labillusion.core.platform.exception.ResourceNotFoundException;
import com.labillusion.core.platform.web.rest.RESTController;
import com.labillusion.core.util.Convert;
import com.labillusion.core.util.StringUtils;
import com.ujoku.context.ActionContext;
import com.ujoku.context.constants.ContextConstants;
import com.ujoku.domain.*;
import com.ujoku.domain.admin.Parameter;
import com.ujoku.request.ReviewHistoryForm;
import com.ujoku.service.*;
import com.ujoku.service.admin.ParametersService;
import com.ujoku.view.builder.GoodsViewBuilder;
import com.ujoku.view.domain.GoodsView;
import com.ujoku.view.domain.ReviewListView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by greg on 2014/10/19.
 */
@RestController
public class GoodsController extends RESTController {

    @Autowired
    private GoodsService service;

    @Autowired
    private GoodsViewBuilder goodsViewBuilder;

    @Autowired
    private CdnService cdnService;

    @Autowired
    private ActionContext actionContext;

    @Autowired
    private FavoriteService favoriteService;

    @Autowired
    private ReviewService reviewService;

    @Autowired
    private WineryService wineryService;

    @Autowired
    private ParametersService parametersService;

    @Autowired
    private MemberService memberService;

    @RequestMapping(value="/goods/{id}", method = RequestMethod.GET)
    @ResponseBody
    public GoodsView getGoodById(@PathVariable int id) throws Exception {
        Goods goods = service.selectById(id);


        GoodsView goodsView = goodsViewBuilder.Create(goods);
        goodsView.setLargeImageList(cdnService.buildGoodsImages(id,CdnService.Goods_Large,goods.getLast_update().getTime()));
        goodsView.setMediumImageList(cdnService.buildGoodsImages(id,CdnService.Goods_Medium,goods.getLast_update().getTime()));
        goodsView.setSmallImageList(cdnService.buildGoodsImages(id,CdnService.Goods_Small,goods.getLast_update().getTime()));
        goodsView.setDescImageList(cdnService.buildGoodsDescImages(id,goods.getLast_update().getTime()));

        if(goods.getWineryId() != null)
        {
            List<Winery> wineries = wineryService.selectList();
            Winery winery = wineries.stream().filter(w->w.getId() == goods.getWineryId()).findFirst().orElse(null);
            goodsView.setWinery(winery);
        }

        Member member = actionContext.getMember();

        if(member == null || member.getDiscount() == null){
            goodsView.setVipPrice(0.00);
        }else{
            goodsView.setVipPrice(goodsView.getPrice() * member.getDiscount());
            if(member!=null){
                List<Favorite> favoriteList=favoriteService.getFavoritesByUserId(member.getUser_id());
                if(favoriteList.stream().anyMatch(g->g.getGoods_id()==goodsView.getGoods_id())){
                    goodsView.setIsFav(true);
                }
            }
        }

        String regEx_html="<[^>]+>";
        String description = goodsView.getDescription();
        if(StringUtils.hasText(description)){
            Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
            Matcher m_html=p_html.matcher(description);
            description = m_html.replaceAll("");
            goodsView.setDescription(description);
        }

        String tags = goodsView.getTags();
        if(StringUtils.hasText(tags)){
            if(tags.startsWith(","))
                tags = tags.replaceFirst(",","");
            if(tags.endsWith(",")){
                tags = tags.substring(0,tags.lastIndexOf(","));
            }
        }
        goodsView.setTags(tags);

        return goodsView;
    }

    @RequestMapping(value="/goods/review", method = RequestMethod.POST)
    @ResponseBody
    public ReviewListView getReviewList(@RequestBody @Valid ReviewHistoryForm form) throws Exception {

        Map<String,Object> query = form.getQueryMap();
        query.put("goods_id", form.getGoods_id());

        List<Review> list = reviewService.getReviewByGoodsId(query);

        if(list == null)
            throw new ResourceNotFoundException("can not found Review");

        list.forEach(review ->{
            String portrait = memberService.getMemberPortrait(review.isPortrait(),review.getMember_id(),review.getPortraitUpdateTime());
            review.setHeadPortraitUrl(portrait);
        });

        int count = reviewService.selectCount(query);

        ReviewListView reviewListView = new ReviewListView();

        reviewListView.setReviewList(list);
        reviewListView.setCount(count);

        return reviewListView;
    }
}
